var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session') // 储存单个用户数据


var indexRouter = require('./routes/index');
var recommendRouter = require('./routes/recommend');
var tagsRouter = require('./routes/tags');
var usersRouter = require('./routes/users');
var searchRouter = require('./routes/search');
var collectionRouter = require('./routes/collection');
var rankingRouter = require('./routes/rank');
var apiRouter = require('./routes/api');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// session中间件
app.use(session({
  secret: 'xmu',
  name:'maker',
  resave: false,
  saveUninitialized: true,
  cookie: {
    maxAge: 60 * 1000 // 设置cookie时间
  },
  rolling: true
}));

// 过滤数据 检测登录状态
app.use((req,res,next)=>{
	if(req.cookies.username == req.session.username & (req.cookies.username != undefined)){
		//相同，则视为已登录状态，跳到下一个中间件
    req.session.login=true
	}else{
    req.session.login=false
	}
  next()
})

// 路由过滤
app.use('/', indexRouter);
app.use('/user', usersRouter);
app.use('/recommend', recommendRouter);
app.use('/tags', tagsRouter);
app.use('/search', searchRouter);
app.use('/collection', collectionRouter);
app.use('/rank', rankingRouter);

app.use('/api', apiRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;